<script setup>
import {Delete, Edit, Folder, Plus, RefreshLeft, Search} from "@element-plus/icons-vue";
import {onBeforeUnmount, onMounted, reactive, ref, watch} from "vue";
import requestUtil from "@/utils/request";
import {ElMessage} from "element-plus";
import TaskDialog from "@/views/monitorCenter/components/TaskDialog.vue";
import GroupDialog from "@/views/monitorCenter/components/groupDialog.vue";

const queryForm = ref({
  name: '',
  pageNum: 1,
  pageSize: 10,
  enableStatus: 3,
  groupID: '',
  typeID: '',
})


const total = ref(0)

const tableData = ref([])

const groupData = ref([])
const typeData = ref([])

const taskDialogVisible = ref(false)
const taskDialogTitle = ref("")
const taskID = ref(-1)

const groupName = ref('')
const groupSortNum = ref(1)

const handleTaskDialogValue = (id) => {
  if (id) {
    taskID.value = id
    taskDialogTitle.value = '修改任务'
    taskDialogVisible.value = true
  } else {
    taskID.value = -1
    taskDialogTitle.value = '新建任务'
    taskDialogVisible.value = true
  }
}
const initGroupAndTypeData = async () => {
  // 获取监控分组数据，和监控类型数据
  try {
    const res = await requestUtil.get('monitor_alert/group/action')
    const data = res.data
    if (data.code === 200) {
      groupData.value = data.group_msg
      typeData.value = data.type_msg
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}
initGroupAndTypeData()

const initTableData = async (val) => {
  try {
    if (val) {
      if (val.id) {
        queryForm.value.groupID = val.id
      }
    }
    const res = await requestUtil.get('monitor_alert/task/action?name=' + queryForm.value.name
        + '&pageNum=' + queryForm.value.pageNum
        + '&pageSize=' + queryForm.value.pageSize
        + '&enableStatus=' + queryForm.value.enableStatus
        + '&groupID=' + queryForm.value.groupID
        + '&typeID=' + queryForm.value.typeID
    )
    const data = res.data
    if (data.code === 200) {
      tableData.value = res.data.msg
      total.value = res.data.total
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}
initTableData()

const handleSizeChange = (pageSize) => {
  queryForm.value.pageNum = 1
  queryForm.value.pageSize = pageSize
  initTableData()
}

const handleCurrentChange = (pageNum) => {
  queryForm.value.pageNum = pageNum
  initTableData()
}

const handleDisable = async (taskID) => {
  try {
    const res = await requestUtil.post('monitor_alert/task/action?activeID=2',
        {'taskID': taskID})
    const data = res.data
    if (data.code === 200) {
      await initTableData()
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}

const handleDelete = async (taskID) => {
  try {
    const res = await requestUtil.del('monitor_alert/task/action',
        {'taskID': taskID})
    const data = res.data
    if (data.code === 200) {
      ElMessage.success('任务删除成功')
      await initTableData()
      await initGroupAndTypeData()
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}

const groupDialogVisible = ref(false)
const groupDialogTitle = ref("")
const groupId = ref(-1)
const treeProps = reactive({
  checkStrictly: false,
})

const handleGroupDialogValue = (id, name, num) => {
  if (id) {
    groupSortNum.value = num
    groupName.value = name
    groupId.value = id;
    groupDialogTitle.value = '修改监控分组';
  } else {
    groupSortNum.value = 1
    groupName.value = ''
    groupId.value = -1;
    groupDialogTitle.value = '添加监控分组'
  }
  groupDialogVisible.value = true
}

const handleDeleteGroup = async (id) => {
  // 删除监控分组
  try {
    const res = await requestUtil.del('monitor_alert/group/action', {"groupID": id})
    const data = res.data
    if (data.code === 200) {
      ElMessage.success('删除成功')
      await initGroupAndTypeData()
    } else {
      ElMessage.error(data.msg)
    }
  } catch (error) {
    console.error('Error fetching table data:', error)
    ElMessage.error('请求失败，请稍后再试')
  }
}

let timer = null;

onMounted(() => {
  // 每隔60秒执行一次
  timer = setInterval(initTableData, 60000);
});
onBeforeUnmount(() => {
  // 离开页面时清除定时器
  if (timer) clearInterval(timer);
});


watch(
    () => queryForm.value.enableStatus,
    () => {
      initTableData()
    }
)
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="5">
        <el-card class="box-card-hard" style="min-width: 100px">
          <template v-slot:header>
            <div class="space-between">
              <span>分组列表</span>
              <el-button @click="handleGroupDialogValue()" size="default" :icon="Plus" type="primary">
                新建
              </el-button>
            </div>
          </template>
          <el-table
              height="600px"
              :data="groupData"
              :tree-props="treeProps"
              row-key="id"
              default-expand-all
              :show-header="false"
              highlight-current-row
              @current-change="initTableData"
          >
            <el-table-column class="clearfix">
              <template #default="scope">
                <el-icon style="margin-right: 5px">
                  <Folder/>
                </el-icon>
                <el-popover
                    placement="bottom-start"
                    trigger="click"
                    :content="scope.row.name"
                >
                  <template #reference>
                    <el-text v-if="scope.row.name.length > 7" class="truncate-text">
                      {{ scope.row.name.slice(0, 7) }}...
                    </el-text>
                    <el-text v-else class="truncate-text">
                      {{ scope.row.name }}
                    </el-text>
                  </template>
                </el-popover>
                <!--                &nbsp;<el-text class="wrap-text">{{ scope.row.name }}</el-text>-->
                <div style="float: right">
                  <span>{{ scope.row.count }}</span>
                  <el-button @click="handleGroupDialogValue(scope.row.id,scope.row.name,scope.row.sort_num)"
                             :icon="Edit"
                             style="margin-left: 20px"
                             size="default"/>
                  <el-popconfirm title="你确定要删除该分组吗？" @confirm="handleDeleteGroup(scope.row.id)">
                    <template #reference>
                      <el-button :icon="Delete" size="default" type="danger"/>
                    </template>
                  </el-popconfirm>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>


      <el-col :span="19">
        <el-card class="box-card-hard">
          <template v-slot:header>
            <div class="space-between">
              <div>
                <el-text class="width-class">监控类型:</el-text>
                <el-select
                    class="width-class"
                    style="width: 150px"
                    v-model="queryForm.typeID"
                    placeholder="请选择"
                    clearable
                >
                  <el-option
                      v-for="item in typeData"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                  />
                </el-select>

                <el-text class="width-class">监控名称:</el-text>
                <el-input
                    class="width-class"
                    style="width: 150px"
                    v-model="queryForm.name"
                    placeholder="请输入监控名"
                />
                <el-button type="primary" :icon="Search" @click="initTableData()">搜索</el-button>
              </div>

              <div class="radio-container">
                <el-button class="width-class" type="primary" :icon="Plus" @click="handleTaskDialogValue()">
                  新建
                </el-button>
                <el-radio-group v-model="queryForm.enableStatus">
                  <el-radio-button label="全部" value="3"/>
                  <el-radio-button label="未启用" value="2"/>
                  <el-radio-button label="已启用" value="1"/>
                </el-radio-group>
                <el-button link @click="initTableData()" class="btn-link">
                  <template #icon>
                    <RefreshLeft/>
                  </template>
                </el-button>
              </div>
            </div>
          </template>

          <el-table :data="tableData"
                    height="600px"
                    stripe
                    style="width: 100%"
          >
            <el-table-column prop="name" label="任务名" width="150" align="center"/>
            <el-table-column prop="mon_group__name" label="监控分组" width="150" align="center"/>
            <el-table-column prop="mon_path" label="监控地址" width="200" align="center"/>
            <el-table-column prop="type" label="监控类型" width="130" align="center"/>
            <el-table-column prop="enable_status" label="任务启用状态" width="150" align="center">
              <template v-slot="scope">
                <span v-if="scope.row.enable_status === 1" class="el-tag el-tag--success">启用</span>
                <span v-else class="el-tag el-tag--danger">禁用</span>
              </template>
            </el-table-column>
            <el-table-column prop="task_status" label="任务执行状态" width="130" align="center">
              <template v-slot="scope">
                <span v-if="scope.row.task_status === 1" class="el-tag el-tag--success">成功</span>
                <span v-else-if="scope.row.task_status === 2" class="el-tag el-tag--danger">失败</span>
                <span v-else class="el-tag el-tag--warning">未验证</span>
              </template>
            </el-table-column>
            <el-table-column prop="mon_freq" label="监控频率" width="130" align="center"
                             :formatter="(row) => `${row.mon_freq}分钟/次`"/>
            <el-table-column prop="update_time" label="更新时间" width="200" align="center"/>
            <el-table-column prop="remark" label="备注" width="200" align="center"/>

            <el-table-column prop="action" label="操作" width="240" fixed="right" align="center">
              <template v-slot="scope">
                <el-popconfirm :title="scope.row.enable_status === 1 ? '你确定要禁用吗？' : '你确定要启用吗？'"
                               @confirm="handleDisable(scope.row.id, scope.row.type,
                           scope.row.mon_path,scope.row.mon_freq,scope.row.host_id,)">
                  <template #reference>
                    <el-button v-if="scope.row.enable_status === 1" type="warning">禁用</el-button>
                    <el-button v-else type="warning">启用</el-button>
                  </template>
                </el-popconfirm>

                <el-button type="primary" @click="handleTaskDialogValue(scope.row.id)">编辑
                </el-button>

                <el-popconfirm v-if="scope.row.code !=='admin'" title="你确定要删除这条记录吗？"
                               @confirm="handleDelete(scope.row.id)">
                  <template #reference>
                    <el-button type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <TaskDialog v-model="taskDialogVisible" :dialogVisible="taskDialogVisible"
                :taskId="taskID" :tableData="tableData"
                :dialogTitle="taskDialogTitle"
                @initTableData="initTableData"
                @initGroupAndTypeData="initGroupAndTypeData"
    ></TaskDialog>

    <GroupDialog v-model="groupDialogVisible" :dialogVisible="groupDialogVisible"
                 :groupName="groupName" :sortNum="groupSortNum" :dialogTitle="groupDialogTitle"
                 @initGroupData="initGroupAndTypeData" :id="groupId"></GroupDialog>
  </div>
  <el-pagination
      :hide-on-single-page="true"
      style="padding: 20px;float: right"
      v-model:currentPage="queryForm.pageNum"
      v-model:page-size="queryForm.pageSize"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
  />
</template>

<style scoped lang="scss">
.wrap-text {
  display: inline-block;
  max-width: 70%; /* 设置最大宽度 */
  white-space: normal; /* 允许换行 */
  word-break: break-all; /* 强制长单词换行 */
  overflow-wrap: break-word; /* 更智能的换行方式 */
}

.space-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
  min-height: 24px;

  .width-class {
    margin-right: 10px;
  }

  .radio-container {
    display: flex;
    justify-content: flex-end;

    .btn-link {
      margin-left: 20px;
      font-weight: bold;
      font-size: 26px;
    }
  }
}


.el-pagination {
  float: right;
  padding: 20px;
  box-sizing: border-box;
}

:deep(th.el-table__cell) {
  word-break: break-word;
  color: var(--text-color);
  height: 40px;
  font-size: 13px;
}

.el-tag--small {
  margin-left: 5px;
}
</style>
